import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/constant/string.dart';
import 'package:mall/event/refresh_event.dart';
import 'package:mall/page/goods/sku_provider.dart';
import 'package:mall/service/goods_service.dart';
import 'package:mall/utils/navigator_util.dart';
import 'package:mall/utils/shared_preferences_util.dart';
import 'package:mall/utils/toast_util.dart';
import 'package:mall/widgets/cart_number.dart';
import 'package:provider/provider.dart';

class CartSkuDialog extends StatelessWidget {
  GoodsService _goodsService = GoodsService();

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Material(
          color: Colors.transparent,
          child: Consumer<SkuProvider>(builder: (context, provider, _) {
            return Container(
              color: Colors.white,
              constraints: BoxConstraints(
                  minHeight: 300, maxHeight: 500, maxWidth: double.infinity),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 20),
                    _buildInfo(provider),
                    SizedBox(height: 20),
                    for (var group in provider.groups)
                      ChangeNotifierProvider<GroupProvider>.value(
                        value: group,
                        child: _RadioGroupItem(),
                      ),
                    _buildOrderCount(provider, context),
                    SizedBox(height: 20),
                    _buildPrice(provider, context),
                    Expanded(
                        child: Stack(
                      alignment: Alignment.bottomLeft,
                      children: <Widget>[
                        SizedBox(
                          height: 100.w,
                          width: double.infinity,
                          child: InkWell(
                              onTap: () => _addCart(provider, context),
                              child: Container(
                                alignment: Alignment.center,
                                color: Colors.deepOrangeAccent,
                                child: Text(
                                  Strings.ADD_CART,
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 30.0.sp),
                                ),
                              )),
                        ),
                      ],
                    ))
                  ]),
            );
          })),
    );
  }

  var parameters;
  var _number = 1;

  bool isStandSku(SkuProvider provider) {
    bool isStand = provider.skus.keys.contains("标准");
    return isStand;
  }

  _buildPrice(SkuProvider provider, BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        SizedBox(width: 20),
        Text("价格：${provider.selectedSkuModel?.price ?? 0}"),
      ],
    );
  }

  _addCart(SkuProvider provider, BuildContext context) {
    SharedPreferencesUtils.getToken().then((value) {
      if (value != null) {
        if (isStandSku(provider)) {
          parameters = {
            "goodsId": provider.skus.values.first.goodsId,
            "productId": provider.skus.values.first.productId,
            "number": _number
          };
        } else {
          parameters = {
            "goodsId": provider.selectedSkuModel.goodsId,
            "productId": provider.selectedSkuModel.productId,
            "number": _number
          };
        }
        Options options = Options(headers: {});
        options.headers[Strings.TOKEN] = value;
        _goodsService.addCart(
          parameters,
          (value) {
            ToastUtil.showToast(Strings.ADD_CART_SUCCESS);
            Navigator.of(context).pop(); //隐藏弹出框
            eventBus.fire(RefreshEvent());
          },
          options: options
        );
      } else {
        NavigatorUtils.goLogin(context);
      }
    });
  }

  int showCount(SkuProvider provider) {
    bool isStand = provider.skus.keys.contains("标准");
    if (isStand) {
      return provider.skus.values.first.count;
    } else {
      return provider?.selectedSkuModel?.count ?? 0;
    }
  }

  _buildOrderCount(SkuProvider provider, BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        SizedBox(width: 20),
        Text("数量："),
        Container(
            margin: EdgeInsets.all(10.w),
            height: 80.h,
            alignment: Alignment.centerLeft,
            child: CartNumberView(1, (number) {
              _number = number;
            })),
        SizedBox(width: 20),
      ],
    );
  }

  _buildInfo(SkuProvider provider) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        SizedBox(width: 20),
        Text("库存：${showCount(provider)}"),
        SizedBox(width: 20),
        Text(provider.selectedSku ?? "请选择"),
      ],
    );
  }
}

class _RadioGroupItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var group = Provider.of<GroupProvider>(context);
    return Container(
      padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
              margin: EdgeInsets.only(top: 16, bottom: 14),
              child: Text(group.groupName, style: TextStyle(fontSize: 14))),
          Wrap(
            alignment: WrapAlignment.start,
            spacing: 16,
            runSpacing: 12,
            children: <Widget>[
              for (var radio in group.radios)
                ChangeNotifierProvider<RadioProvider>.value(
                  value: radio,
                  child: _RadioButton(),
                ),
            ],
          ),
        ],
      ),
    );
  }
}

class _RadioButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var radio = Provider.of<RadioProvider>(context);
    var group = Provider.of<GroupProvider>(context);
    bool isSelect = radio.radioName == group.selectedValue;
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: FlatButton(
        child: Text(radio.radioName, style: TextStyle(fontSize: 12)),
        onPressed: radio.isDisabled
            ? null
            : () {
                if (group.selectedValue != radio.radioName) {
                  //选中
                  group.changeSelectValue(radio.radioName);
                } else {
                  //重复点击取消选中
                  group.changeSelectValue(null);
                }
              },
        color: isSelect ? Color(0x1AFF6631) : Color(0xFFF7F7F7),
        textColor: isSelect ? Color(0xFFFF6732) : Color(0xff333333),
        disabledTextColor: Color(0xff999999),
        shape: StadiumBorder(
            side: BorderSide(
                style: BorderStyle.solid,
                color: isSelect ? Color(0xFFFF6732) : Color(0xFFF7F7F7))),
      ),
    );
  }
}
